package com.acooly.module.openapi.client.provider.bosc.security;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.acooly.core.common.exception.BusinessException;
import com.acooly.module.openapi.client.provider.bosc.BoscConstants;
import com.acooly.module.openapi.client.provider.bosc.BoscProperties;
import com.acooly.module.safety.signature.Signer;
import com.alibaba.fastjson.JSONObject;
import com.koalii.crypto.SignUtil;

@Service
public class BoscSigner implements Signer<String, BoscProperties> {

	@Override
	public String sign(String plain, BoscProperties key) {
		SignUtil signUtil = new SignUtil();
		try {
			signUtil.initSignCertAndKey(key.getCertpfx(), key.getCertpfxPwd());
			// 签名结果Base64编码
			String signData = signUtil
					.signData(URLEncoder.encode(String.format("%1$s---%2$s", plain, key.getKey()), "UTF-8").getBytes());
			// String signData ="";
			signData = signData.replaceAll("\r", "");
			signData = signData.replaceAll("\n", "");
			// 获得签名证书的Base64编码
			String signCert = signUtil.getEncodedSignCert();
			signCert = signCert.replaceAll("\r", "");
			signCert = signCert.replaceAll("\n", "");

			Map<String, String> map = new HashMap<>();
			map.put("signData", signData);
			map.put("signCert", signCert);

			return JSONObject.toJSONString(map);
		} catch (Exception e) {
			throw new BusinessException("签名处理异常");
		}
	}

	@Override
	public void verify(String plain, BoscProperties key, String sign) {
		// TODO Auto-generated method stub

	}

	@Override
	public String getSinType() {
		return BoscConstants.SIGNER_KEY;
	}

}
